package com.bawei.module_mine.ui

import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_mvi.Router
import com.bawei.lib_mvi.base.BaseActivity
import com.bawei.module_mine.databinding.ActivityOrderBinding
import com.bawei.lib_common.manager.GlobalDataManager
import com.bawei.lib_net.msgbus.LiveDataBus
import com.tencent.mmkv.MMKV
import android.os.Bundle
import android.widget.Toast
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bawei.module_mine.http.intent.LoginIntent
import com.bawei.module_mine.http.state.LoginState
import com.bawei.module_mine.http.viewModel.LoginViewModel
import com.bawei.module_mine.model.Record
import com.bumptech.glide.Glide
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

@Route(path = "/mine/OrderActivity")
class OrderActivity : BaseActivity() {
    private val binding by lazy {
        ActivityOrderBinding.inflate(layoutInflater)
    }

    private val loginViewModel by viewModels<LoginViewModel>()
    private lateinit var mineAdapter: MineRecordAdapter


    override fun initView() {
        // 先显示本地缓存
        val cartCount = MMKV.defaultMMKV().getInt("cart_count", 0)
        val collectCount = MMKV.defaultMMKV().getInt("collect_count", 0)
        binding.shoppingNum.text = cartCount.toString()
        binding.collectNum.text = collectCount.toString()
        super.initView()
        binding.tvOrderMore.setOnClickListener {
            ARouter.getInstance().build("/module_mall/OrderListActivity").navigation()
        }
        binding.ivBack.setOnClickListener {
            finish()
        }
        binding.addressLl.setOnClickListener {
            ARouter.getInstance().build(Router.Ui.ADDRESS_ACTIVITY).navigation()
        }
        binding.myShowCase.setOnClickListener {
            ARouter.getInstance().build(Router.Ui.GOODS_SHOW_ACTIVITY).navigation()
        }
        binding.collectLl.setOnClickListener {
            ARouter.getInstance().build(Router.Ui.COLLECT_SHOP_ACTIVITY).navigation()
        }
        binding.shopLl.setOnClickListener {
            ARouter.getInstance().build(Router.Ui.SHOP_ACTIVITY).navigation()
        }
        // 监听购物车数量变化
        LiveDataBus.with<Int>("cart_count").observe(this) { count ->
            binding.shoppingNum.text = count?.toString() ?: "0"
        }
        // 监听收藏数量变化
        LiveDataBus.with<Int>("collect_count").observe(this) { count ->
            binding.collectNum.text = count?.toString() ?: "0"
        }
        // 初始化RecyclerView
        binding.rvFootprint.layoutManager = LinearLayoutManager(this)
        mineAdapter = MineRecordAdapter(emptyList())
        binding.rvFootprint.adapter = mineAdapter
        // 请求数据
        lifecycleScope.launch {
            loginViewModel.intents.send(LoginIntent.Mine)
        }
        observeMineList()
        initCountDisplay()
    }
    
    /**
     * 初始化数量显示
     */
    private fun initCountDisplay() {
        // 显示当前购物车数量
        binding.shoppingNum.text = GlobalDataManager.getCurrentCartCount().toString()
        // 显示当前收藏数量
        binding.collectNum.text = GlobalDataManager.getCurrentCollectCount().toString()
    }

    private fun observeMineList() {
        lifecycleScope.launch {
            loginViewModel.state.collect { state ->
                when (state) {
                    is LoginState.MineSuccess -> {
                        mineAdapter.updateData(state.data.records)
                    }
                    is LoginState.Error -> {
                        Toast.makeText(this@OrderActivity, state.error, Toast.LENGTH_SHORT).show()
                    }
                    else -> {}
                }
            }
        }
    }

    override fun getLayoutRootView(): View {
        return binding.root
    }
}

// Adapter类
class MineRecordAdapter(private var list: List<Record>) : RecyclerView.Adapter<MineRecordAdapter.VH>() {
    class VH(val binding: com.bawei.module_mine.databinding.ItemMineRecordBinding) : RecyclerView.ViewHolder(binding.root)
    override fun onCreateViewHolder(parent: android.view.ViewGroup, viewType: Int): VH {
        val binding = com.bawei.module_mine.databinding.ItemMineRecordBinding.inflate(android.view.LayoutInflater.from(parent.context), parent, false)
        return VH(binding)
    }
    override fun onBindViewHolder(holder: VH, position: Int) {
        val record = list[position]
        Glide.with(holder.itemView.context).load(record.mainImgUrl).into(holder.binding.mine)
        holder.binding.mineTv.text = record.title
        holder.binding.mineDec.text = "¥${record.purchasePrice}"
        holder.binding.mineDec.setOnClickListener {
            ARouter.getInstance().build(Router.Ui.SHOP_DETAIL_ACTIVITY).withInt("shopId", record.id).navigation()
        }
    }
    override fun getItemCount() = list.size
    fun updateData(newList: List<Record>) {
        list = newList
        notifyDataSetChanged()
    }
}